package com.lyfei.yd.admin.web;

import com.lyfei.yd.common.core.domain.AjaxResult;
import com.lyfei.yd.domain.dto.CategoryDto;
import com.lyfei.yd.domain.dto.PageQueryDto;
import com.lyfei.yd.domain.entity.Category;
import com.lyfei.yd.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@Validated
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/all")
    public AjaxResult getAll(){
        Map<String, List<Category>> categories = new HashMap<>();

        categories.put("roots", categoryService.getRootCategories());
        categories.put("subs", categoryService.getAllSubCategories());

        return AjaxResult.success(categories);
    }

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return AjaxResult.success(categoryService.getById(id));
    }

    @PostMapping("/add")
    public AjaxResult addCategory(@RequestBody CategoryDto dto) {
        this.categoryService.createCategory(dto);
        return AjaxResult.success();
    }

    @PostMapping("/update/{id}")
    public AjaxResult updateCategory(@RequestBody @Validated CategoryDto dto,
                                     @PathVariable Long id) {
        this.categoryService.updateCategory(dto, id);
        return AjaxResult.success();
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        this.categoryService.deleteCategory(id);
        return AjaxResult.success();
    }

    @GetMapping("/rootPage")
    public AjaxResult rootPage(PageQueryDto dto) {
        return AjaxResult.success(categoryService.getCategoriesByPage(dto, true));
    }

    @GetMapping("/subPage/{id}")
    public AjaxResult subPage(PageQueryDto dto, @PathVariable Long id) {
        return AjaxResult.success(categoryService.getSubCategoriesByPage(dto, id));
    }

    @GetMapping("/subList")
    public AjaxResult subList() {
        return AjaxResult.success(categoryService.getAllSubCategories());
    }
}
